//
//  TowCodeViewController.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/9/19.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import SVProgressHUD
import SwiftyUserDefaults

class TowCodeViewController: BaseViewController ,UITableViewDelegate, UITableViewDataSource{

    var myCode : String!
    override func viewDidLoad() {
        super.viewDidLoad()
        layoutNav()
        makeBaseUI()
        // Do any additional setup after loading the view.
    }
    
    func layoutNav(){
        self.title = XALanguageManager.getString(key: "我的二维码")
    }
    
    //MARK: - tableView Delegate And DataSource
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        if cell == nil {
            cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
        }
        cell?.backgroundColor = UIColor.clear
        cell?.textLabel?.text = ""
        return cell!
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let backView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kScreenHeight))
        
        
        backView.backgroundColor = UIColor.clear
        let topImageView = UIImageView(frame: CGRect(x: 75*_kScreenWidth/2, y: 100*_kScreenWidth, width: 300*_kScreenWidth, height: 48*_kScreenWidth))
        topImageView.image = UIImage.init(named: "色相_饱和度 1@2x")
        backView.addSubview(topImageView)
        
        let bottombackView = UIImageView(image: UIImage.init(named: "矢量智能对象@2x"))
        backView.addSubview(bottombackView)
        
        
        
        bottombackView.snp.makeConstraints { (make) in
            make.top.equalTo(topImageView.snp.bottom).offset(45*_kScreenWidth)
            make.centerX.equalTo(backView)
            make.size.equalTo(CGSize(width: 330*_kScreenWidth, height: 442*_kScreenWidth))
        }
        
        
        let titleLabel = UILabel()
        titleLabel.text = "My invitation code"
        backView.addSubview(titleLabel)
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        titleLabel.textAlignment = .center
        titleLabel.textColor = UIColor("#418DFF")
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(bottombackView).offset(50*_kScreenWidth)
            make.centerX.equalTo(backView)
            make.size.equalTo(CGSize(width: 330*_kScreenWidth, height: 17))
        }
        
        let codeLabel = UILabel()
        codeLabel.font = UIFont.boldSystemFont(ofSize: 39)
        codeLabel.text = Defaults[.vip_code]
        codeLabel.textAlignment = .center
        backView.addSubview(codeLabel)
        codeLabel.textColor = UIColor("#418DFF")
        codeLabel.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(20*_kScreenWidth)
            make.centerX.equalTo(backView)
            make.size.equalTo(CGSize(width: 330*_kScreenWidth, height: 39))
        }
        
        let copyBtn = UIButton()
        copyBtn.setTitle("Copy", for: .normal)
        backView.addSubview(copyBtn)
        copyBtn.backgroundColor = UIColor("#418DFF")
        copyBtn.snp.makeConstraints { (make) in
            make.top.equalTo(codeLabel.snp.bottom).offset(20*_kScreenWidth)
            make.centerX.equalTo(backView)
            make.size.equalTo(CGSize(width: 110, height: 30))
        }
        copyBtn.layer.cornerRadius = 5
        copyBtn.addTarget(self, action: #selector(TowCodeViewController.copyCode), for: .touchUpInside)
        
        let detailLabel = UILabel()
        detailLabel.text = ""
        backView.addSubview(detailLabel)
        
        detailLabel.font = UIFont.systemFont(ofSize: 15)
        //        titleLabel.textAlignment = .center
        detailLabel.textColor = UIColor("#418DFF")
        detailLabel.numberOfLines = 0
        detailLabel.sizeToFit()
        detailLabel.font = UIFont.systemFont(ofSize: 14)
        detailLabel.snp.makeConstraints { (make) in
            make.top.equalTo(copyBtn.snp.bottom).offset(20*_kScreenWidth)
            make.centerX.equalTo(backView)
            make.width.equalTo (280*_kScreenWidth)
            //            make.size.equalTo(CGSize(width: 300*_kScreenWidth, height: 17))
        }
        
        
        let codeImage = UIImageView()
        backView.addSubview(codeImage)
        codeImage.snp.makeConstraints { (make) in
            make.top.equalTo(detailLabel.snp.bottom).offset(20*_kScreenWidth)
            make.centerX.equalTo(backView)
            make.size.equalTo(CGSize(width: 135*_kScreenWidth, height: 135*_kScreenWidth))
        }
        
        let url = "https://www.pgyer.com/NErM";
        //你的头像（可以为nil）
        let headerImage = UIImage(named: "")
        //生成图片并且显示
        codeImage.image = setupQRCodeImage(url, image: headerImage)
        
        
        
        let codeImage1 = UIImageView()
        backView.addSubview(codeImage1)
        codeImage1.snp.makeConstraints { (make) in
            make.top.equalTo(codeImage.snp.bottom).offset(100)
            make.centerX.equalTo(backView)
            make.size.equalTo(CGSize(width: 135*_kScreenWidth, height: 135*_kScreenWidth))
        }
        
        let url1 = "http://renedescartes.io/dke.apk";
        //你的头像（可以为nil）
        let headerImage1 = UIImage(named: "")
        //生成图片并且显示
        codeImage1.image = setupQRCodeImage(url1, image: headerImage1)
        
        let bottomLabel = UILabel()
        bottomLabel.text = "iOS扫我下载～"
        backView.addSubview(bottomLabel)
        bottomLabel.font = UIFont.systemFont(ofSize: 12)
        bottomLabel.textAlignment = .center
        bottomLabel.textColor = UIColor("909090")
        bottomLabel.snp.makeConstraints { (make) in
            make.top.equalTo(codeImage.snp.bottom).offset(15)
            make.centerX.equalTo(codeImage1)
            make.size.equalTo(CGSize(width: 330*_kScreenWidth, height: 17))
        }
        
        
        
        let bottomLabel1 = UILabel()
        bottomLabel1.text = "Android扫我下载～"
        backView.addSubview(bottomLabel1)
        bottomLabel1.font = UIFont.systemFont(ofSize: 12)
        bottomLabel1.textAlignment = .center
        bottomLabel1.textColor = UIColor("909090")
        bottomLabel1.snp.makeConstraints { (make) in
            make.top.equalTo(codeImage1.snp.bottom).offset(15)
            make.centerX.equalTo(codeImage1)
            make.size.equalTo(CGSize(width: 330*_kScreenWidth, height: 17))
        }
        
        let LineView = UIView()
        LineView.backgroundColor = UIColor("#293163")
        
        backView.addSubview(LineView)
        LineView.snp.makeConstraints { (make) in
            make.left.equalTo(backView).offset(15)
            make.right.equalTo(backView).offset(-15)
            make.top.equalTo(codeImage.snp.bottom).offset(50)
            make.height.equalTo(1)
        }
        
        
        let LineView1 = UIView()
        LineView1.backgroundColor = UIColor("#293163")
        
        backView.addSubview(LineView1)
//        LineView.snp.makeConstraints { (make) in
//            make.left.equalTo(self.view).offset(15)
//            make.right.equalTo(self.view).offset(-15)
//            make.top.equalTo(codeImage1.snp.bottom)
//            make.height.equalTo(1)
//        }
        
        
        return backView
        
        
    }
    
    //footer height
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    // row height
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 0.00000001
    }
    // header height
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 750 + 100
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return nil
    }
    
    // row num
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    // 组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    //点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    override func willMove(toParentViewController parent: UIViewController?) {
        
    }
    
    // MARK: - 懒加载
    private lazy var myTableView:UITableView = {
        let myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight), style: UITableViewStyle.grouped)
        myTableView.delegate = self
        myTableView.dataSource = self
        myTableView.backgroundColor = UIColor.clear
        myTableView.separatorColor = UIColor.clear
        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        return myTableView
    }()
    
    
    func makeBaseUI() {
        let count = 2
        var myheight : CGFloat!
        myheight = 64
        if UIDevice.current.isX(){
            myheight = 84
        }
        
        let frame = CGRect(x: 0, y: myheight, width: view.bounds.width, height: view.bounds.height)
        var contentViews = [UIView]()
        var titles = [String]()
        let tempArr = [XALanguageManager.getString(key: "苹果下载"),XALanguageManager.getString(key: "安卓下载")]
        
        for i in 0..<count {
            let vc = testViewController()
            if i==0 {
                vc.isIOS = true
            }
            addChildViewController(vc)
            contentViews.append(vc.view)
            titles.append(tempArr[i])
        }
        
        let segmentView = SSSegmentedView(frame: frame, titles: titles, contentViews: contentViews)
        segmentView.sliderStyle = .center
        segmentView.isShowBottomLine = false
        segmentView.viewIndex = { index in
            print("----滚动位置\(index)")
        }
        
        view.addSubview(segmentView)
        
        
        
        //self.view.addSubview(self.myTableView)
        
    }
    
    //MARK: -传进去字符串,生成二维码图片
    func setupQRCodeImage(_ text: String, image: UIImage?) -> UIImage {
        //创建滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setDefaults()
        //将url加入二维码
        filter?.setValue(text.data(using: String.Encoding.utf8), forKey: "inputMessage")
        //取出生成的二维码（不清晰）
        if let outputImage = filter?.outputImage {
            //生成清晰度更好的二维码
            let qrCodeImage = setupHighDefinitionUIImage(outputImage, size: 300)
            //如果有一个头像的话，将头像加入二维码中心
            if var image = image {
                //给头像加一个白色圆边（如果没有这个需求直接忽略）
                image = circleImageWithImage(image, borderWidth: 50, borderColor: UIColor.white)
                //合成图片
                let newImage = syntheticImage(qrCodeImage, iconImage: image, width: 100, height: 100)
                
                return newImage
            }
            
            return qrCodeImage
        }
        
        return UIImage()
    }
    
    //image: 二维码 iconImage:头像图片 width: 头像的宽 height: 头像的宽
    func syntheticImage(_ image: UIImage, iconImage:UIImage, width: CGFloat, height: CGFloat) -> UIImage{
        //开启图片上下文
        UIGraphicsBeginImageContext(image.size)
        //绘制背景图片
        image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
        
        let x = (image.size.width - width) * 0.5
        let y = (image.size.height - height) * 0.5
        iconImage.draw(in: CGRect(x: x, y: y, width: width, height: height))
        //取出绘制好的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        //返回合成好的图片
        if let newImage = newImage {
            return newImage
        }
        return UIImage()
    }
    @objc func copyCode() {
        UIPasteboard.general.string = Defaults[.vip_code]
        
        SVProgressHUD.showSuccess(withStatus: XALanguageManager.getString(key: "复制成功"))
        SVProgressHUD.dismiss(withDelay: 0.5)
        
        

    }
    //MARK: - 生成高清的UIImage
    func setupHighDefinitionUIImage(_ image: CIImage, size: CGFloat) -> UIImage {
        let integral: CGRect = image.extent.integral
        let proportion: CGFloat = min(size/integral.width, size/integral.height)
        
        let width = integral.width * proportion
        let height = integral.height * proportion
        let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImage = context.createCGImage(image, from: integral)!
        
        bitmapRef.interpolationQuality = CGInterpolationQuality.none
        bitmapRef.scaleBy(x: proportion, y: proportion);
        bitmapRef.draw(bitmapImage, in: integral);
        let image: CGImage = bitmapRef.makeImage()!
        return UIImage(cgImage: image)
    }
    
    //生成边框
    func circleImageWithImage(_ sourceImage: UIImage, borderWidth: CGFloat, borderColor: UIColor) -> UIImage {
        let imageWidth = sourceImage.size.width + 2 * borderWidth
        let imageHeight = sourceImage.size.height + 2 * borderWidth
        
        UIGraphicsBeginImageContextWithOptions(CGSize(width: imageWidth, height: imageHeight), false, 0.0)
        UIGraphicsGetCurrentContext()
        
        let radius = (sourceImage.size.width < sourceImage.size.height ? sourceImage.size.width:sourceImage.size.height) * 0.5
        let bezierPath = UIBezierPath(arcCenter: CGPoint(x: imageWidth * 0.5, y: imageHeight * 0.5), radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
        bezierPath.lineWidth = borderWidth
        borderColor.setStroke()
        bezierPath.stroke()
        bezierPath.addClip()
        sourceImage.draw(in: CGRect(x: borderWidth, y: borderWidth, width: sourceImage.size.width, height: sourceImage.size.height))
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
